
from django.contrib.auth import authenticate

from accounts.models import RegularUser
from tourist_spot.models import TouristSpot

from django import forms
from django.contrib.auth.forms import AuthenticationForm
from django.core.exceptions import ValidationError


class BootStrapForm(forms.Form):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        # 循环ModelForm中的所有字段，给每个字段的插件设置
        for name, field in self.fields.items():
            # 字段中有属性，保留原来的属性，没有属性才添加
            if field.widget.attrs:
                field.widget.attrs["class"] = 'form-control'
                field.widget.attrs['placeholder'] = field.label
            else:
                field.widget.attrs = {
                    "class": "form-control",
                    "placeholder": field.label
                }


class TouristSpotReviewForm(forms.ModelForm):
    class Meta:
        model = TouristSpot
        fields = ['status', 'rejection_reason']
        widgets = {
            'status': forms.Select(choices=TouristSpot.STATUS_CHOICES),
            'rejection_reason': forms.Textarea(attrs={'rows': 3}),
        }


class LoginForm(BootStrapForm):
    username = forms.CharField(
        label='用户名',
        widget=forms.TextInput,
        required=True
    )
    password = forms.CharField(
        label='密码',
        widget=forms.PasswordInput(render_value=True),
        required=True
    )

    def clean(self):
        cleaned_data = super().clean()
        username = cleaned_data.get('username')
        password = cleaned_data.get('password')

        if username and password:
            self.user = authenticate(username=username, password=password)
            if not self.user:
                raise forms.ValidationError("用户名或密码错误")
            if not self.user.is_active:
                raise forms.ValidationError("该账号已被禁用")
        return cleaned_data



class RoleLoginForm(AuthenticationForm):
    ROLE_CHOICES = [
        ('user', '普通用户'),
        ('admin', '管理员'),
        ('culture', '文旅机构'),
    ]

    role = forms.ChoiceField(
        choices=ROLE_CHOICES,
        widget=forms.HiddenInput(),
        initial='user'
    )

    remember_me = forms.BooleanField(
        required=False,
        widget=forms.CheckboxInput(attrs={'class': 'form-check-input'})
    )

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['username'].widget.attrs.update({
            'class': 'form-control',
            'placeholder': '请输入用户名',
            'autofocus': True
        })
        self.fields['password'].widget.attrs.update({
            'class': 'form-control',
            'placeholder': '请输入密码'
        })

    def confirm_login_allowed(self, user):
        if not user.is_active:
            raise ValidationError(
                "该账户已被禁用",
                code='inactive',
            )


class UserProfileForm(forms.ModelForm):
    class Meta:
        model = RegularUser
        fields = [
            'nickname', 'gender', 'birth_date', 'avatar',
            'province', 'city', 'district',
            'interests', 'travel_frequency', 'budget_preference',
            'wechat_id', 'bio'
        ]
        widgets = {
            'birth_date': forms.DateInput(attrs={'type': 'date'}),
            'bio': forms.Textarea(attrs={'rows': 3}),
            'interests': forms.TextInput(attrs={
                'placeholder': '例如: 历史人文,自然风光,美食探店'
            }),
        }
        labels = {
            'nickname': '昵称',
            'gender': '性别',
            'birth_date': '出生日期',
            'avatar': '头像',
            'province': '省份',
            'city': '城市',
            'district': '区县',
            'interests': '兴趣标签',
            'travel_frequency': '年旅游次数',
            'budget_preference': '消费偏好',
            'wechat_id': '微信ID',
            'bio': '个人简介',
        }